/**
 * 
 */
package com.autoscript.ui.template.function;

import java.io.File;
import java.util.List;

import com.autoscript.ui.helper.FileCtrlUtils;
import com.autoscript.ui.helper.StringHelper;
import com.autoscript.ui.helper.UIPropertyHelper;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * @author Administrator
 * 读取文本文件
 */
public class ReadTextFile implements TemplateMethodModel {

	@Override
	public Object exec(List args) throws TemplateModelException {
		//格式: ReadTextFile(文件名,字符集)
		if(args.size()!=2 ){
			throw new TemplateModelException(UIPropertyHelper.getString("exception.func_para_number_not_match","ReadTextFile",args.size(),"2"));
		}
		String fileName;
		fileName = (String) args.get(0);
		String encoding;
		encoding = (String) args.get(1);
		if(StringHelper.isEmpty(fileName))
			throw new TemplateModelException(UIPropertyHelper.getString("exception.object_is_empty", "文件名"));
		if(StringHelper.isEmpty(encoding))
			throw new TemplateModelException(UIPropertyHelper.getString("exception.object_is_empty", "字符集"));
		if(FileCtrlUtils.isExists(fileName)) {
			try {
				return FileCtrlUtils.readFileToString(new File(fileName), encoding);
			} catch (Exception e) {
				e.printStackTrace();
				throw new TemplateModelException(e.getMessage());
			}
		} else
			throw new TemplateModelException(UIPropertyHelper.getString("exception.file_not_exist", fileName));
			
	}

}
